<?php
class Admin_Model_User {
	
	protected $_db = NULL;
	
	/**
	 * construct
	 */
	public function __construct()
	{		
		$this->_db = Zend_Db_Table::getDefaultAdapter();		
	}
		
	/**
	 * @param array $data
	 * @param int $uid
	 * @return int|number
	 */
	public function insert($data, $uid=0)
	{
		$data['created_time'] = date('Y-m-d H:i:s');
		$data['updated_time'] = date('Y-m-d H:i:s');		
		try {
			unset($data['id']);
			$result = $this->_db->insert('users', $data);
			return $result;
		} catch (Exception $e) {
			return 0;
		}
	}
	
	/**
	 * update
	 * 
	 * @param array $data
	 * @param int $uid
	 * @return int|number
	 */
	public function update($data, $uid=0)
	{			
		try {
			$id = $data['id'];
			unset($data['id']);
			$result = $this->_db->update('users', $data, "id={$id}");
			return $result;
		} catch (Zend_Db_Adapter_Exception $e) {
			return 0;
		}
	}
	
	/**
	 * active
	 * 
	 * @param array $data
	 * @param int $uid
	 * @return int|number
	 */
	public function updateStatus($data, $ids)
	{		
		$data['updated_time'] = date('Y-m-d H:i:s');		
		try {		
			$result = $this->_db->update('users', $data, "id IN ({$ids})");
			return $result;
		} catch (Zend_Db_Adapter_Exception $e) {
			return 0;
		}
	}
	
	/**
	 * get list manager user 	 
	 */
	public function getListManager()
	{
		$select = $this->_db->select()
							->from (array('u' => 'users'))
							->where ('u.role_id=?', 1)
							->orWhere('u.role_id=?', 2);
		return $this->_db->fetchAll($select);
	}
	
	/**
	 * get list user 	 
	 */
	public function getList($where=array())
	{
		$select = $this->_db->select()->from (array('u' => 'users'));	
		if (!empty($where))	$select->where(implode(' AND ', $where));						
		return $this->_db->fetchAll($select);
	}
	
	/**
	 * get list role 	 
	 */
	public function getListRole()
	{
		$select = $this->_db->select()->from (array('u' => 'acl_roles'));							
		return $this->_db->fetchAll($select);
	}
	
	/**
	 * Check exist value
	 * 
	 * @param string $value
	 * @param string $field
	 * @return array 
	 */
	public function isExistValue($value, $field='username') {
		$select = $this->_db->select()
							->from('users')
							->where("{$field}=\"{$value}\"");
		return $this->_db->fetchRow($select);
	}
	
	/**
	 * Get user detail by user id
	 * 
	 * @param int $id
	 * @return array 
	 */
	public function getDetail($id)
	{
		$select = $this->_db->select()
							->from(array('u' => 'users'))	
							->where('u.id=?', $id);	
		$result = $this->_db->fetchRow($select);
		return $result;
	}
}
